import os.path
import openpyxl


class Reader:
    """
    pip install openpyxl
    """

    def __init__(self):
        self.workbook = None  # 定义工作book
        self.sheet = None  # 每个sheet
        self.rows = None  # 具体的行数
        self.r = 0  # 当前读取到的行数

    def open_excel(self, srcfile):  # 打开文件
        if not os.path.isfile(srcfile):  # 如果文件不存在
            print("%s not exist！" % srcfile)
            return

        openpyxl.workbook.encoding = 'utf-8'  # 读取Excel的编码
        self.workbook = openpyxl.load_workbook(filename=srcfile)
        self.sheet = self.workbook[self.workbook.sheetnames[0]]  # 设置从第一个sheet开始读取
        self.rows = self.sheet.max_row  # 设置行数 # 设置rows为当前sheet的行数
        self.rows = 0  # 设置默认读取的行数为0、
        return

    def get_sheets(self):  # 获取sheet页面
        sheets = self.workbook.sheetnames
        return sheets

    def set_sheets(self, name):  # 替换sheet
        self.sheet = self.workbook[name]
        self.rows = self.sheet.max_row
        self.r = 0
        return

    def readline(self):  # 逐行读取的方法
        lines = []
        for row in self.sheet.rows:
            line = []
            for cell in row:
                if cell.value is None:
                    line.append('')
                else:
                    line.append(str(cell.value))
            lines.append(line)
            print(line)
        return lines


if __name__ == '__main__':
    r = Reader()
    r.open_excel('../../lib/一手app-test.xlsx')
    sheets = r.get_sheets()
    for sheet in sheets:
        r.set_sheet(sheet)
        r.readline()
